#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "Stack.h"

void Swap(int* p1, int* p2)
{
	int tem = *p1;
	*p1 = *p2;
	*p2 = tem;
}

void QuickSort(int* a, int begin, int end)
{
	ST st;
	STInit(&st);
	STPush(&st,end);
	STPush(&st, begin);
	while (!STEmpty(&st))
	{
		int left = STTop(&st);
		STPop(&st);
		int right = STTop(&st);
		STPop(&st);
		//keyi
		int prev = left, keyi = left, cur = left + 1;
		while (cur <= right)
		{
			if (a[cur] < a[keyi] && prev++ != cur)
			{
				Swap(&a[cur], &a[prev]);
			}
			cur++;
		}
		Swap(&a[prev], &a[keyi]);
		keyi = prev;

		//[left ,keyi - 1] keyi [ keyi + 1,end]

		if (left < keyi - 1)
		{
			STPush(&st, keyi - 1);
			STPush(&st, left);
		}
		if (keyi + 1 < end)
		{
			STPush(&st, end);
			STPush(&st, keyi + 1);
		}

	}

	STDestroy(&st);
}

void PrintArray(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

void Test()
{
	int a[] = { 8,2,4,5,2,1,9,0,7 };
	int len = sizeof(a) / sizeof(int);
	PrintArray(a, len);
	QuickSort(a, 0, len - 1);
	PrintArray(a, len);
}

int main()
{
	Test();

	return 0;
}
